package com.training.admin.web.controller.report;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.eclipse.jetty.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.utils.WebUtils;
import com.training.admin.entity.principal.Principal;
import com.training.admin.entity.project.ProjectPhaseCourse;
import com.training.admin.entity.project.TrainingSurveyResult;
import com.training.admin.entity.search.CourseRecordReportSearch;
import com.training.admin.entity.security.Login;
import com.training.admin.service.PrincipalService;
import com.training.admin.service.ReportService;
import com.training.admin.service.TrainingSurveyResultService;
import com.training.admin.web.controller.view.ExcelTemplateView;

/**
 * 
 * @author sjh
 *
 */
@Controller
@RequestMapping("")
@MenuSetting("menu-report")
public class CourseRecordsController {
    
    private static final Logger logger = LoggerFactory.getLogger(TrainerReportController.class);

    @Autowired
    private PrincipalService principalService;

    @Autowired
    private ReportService reportService;
    @Autowired
    private TrainingSurveyResultService trainingSurveyResultService;
    /**
     * 讲师授课记录
     * 
     * @param page
     * @return
     */
    @RequestMapping(value = "/course-records", method = RequestMethod.GET)
    @MenuSetting("submenu-course-record")
    public ModelAndView courseRecordReportSearch(Page page) {
        ModelAndView modelAndView = new ModelAndView("report/course-record-report-search");

        return modelAndView;
    }

    /**
     * 讲师授课记录提交
     * 
     * @param page
     * @return
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/course-records", method = RequestMethod.GET, params = "filter")
    @MenuSetting("submenu-course-record")
    public ModelAndView onCourseRecordReportSearch(CourseRecordReportSearch courseRecordReportSearch, Page page,
            HttpServletRequest request) {
        
        
        ModelAndView modelAndView = new ModelAndView("report/course-record-report");

        Login login = (Login) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Principal principal = principalService.loadByEmail(login.getEmail());
        if (principal.getAuthority().equals("ROLE_SUPER_USER")) {
            // 系统管理员
            // do nothing
        } else if (principal.getAuthority().equals("ROLE_DEPARTMENT_USER")) {
            // 事业部负责人
            courseRecordReportSearch.setDepartmentId(principal.getDepartmentId());
        }

        int totals = reportService.count(courseRecordReportSearch);
        if (totals > 0) {

            List courseList = reportService.search(courseRecordReportSearch, page.with(totals));
            
            List<ProjectPhaseCourse> courses = new ArrayList<ProjectPhaseCourse>();
            for (int i = 0; i < courseList.size(); i++) {
                ProjectPhaseCourse projectPhaseCourse = (ProjectPhaseCourse) courseList.get(i);
                // Course course= projectPhaseCourse.getCourse();
                // set survey result / suggestion to each course
                List<TrainingSurveyResult> trainingSurveyResultList = trainingSurveyResultService.listByProjectPhaseCourse(projectPhaseCourse.getId());
                int trainerTotalScore = 0;
                int scoreTotalScore = 0;
                int trainerScoreCount = 0;
                int courseScoreCount = 0;
                
                int j = 0;
                String suggestion = "";
                for (; j < trainingSurveyResultList.size(); j++) {
                    TrainingSurveyResult trainingSurveyResult = trainingSurveyResultList.get(j);
                    
                    //check question
                    if (trainingSurveyResult.getQuestion().contains("主题课程是否满足您的期望、对您的管理工作有所帮助？") ||
                            trainingSurveyResult.getQuestion().contains("授课逻辑清晰易懂，呈现演绎生动有趣，能够吸引您积极投入对主题内容的学习？") ||
                                trainingSurveyResult.getQuestion().contains("对主题内容有深度的理解，善于联系真实的工作场景与实际的管理挑战") ||
                                    trainingSurveyResult.getQuestion().contains("主题课程进行整体评价")){
                        int score = 0;
                        try {
                            score = Integer.parseInt(trainingSurveyResult.getInputValue());
                            trainerTotalScore += score;
                            trainerScoreCount++;
                        } catch (Exception exx) {
                            logger.warn(trainingSurveyResult.getQuestion() + ":::::::"
                                    + trainingSurveyResult.getInputValue() + "  " + exx.getMessage());
                        }
                    }
                    
                }
                if (j > 0) {
                    if (trainerScoreCount > 0) {
                        BigDecimal bd = new BigDecimal(trainerTotalScore * 1.0 / (trainerScoreCount));
                        double d1 =bd.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
                        projectPhaseCourse.setTrainerSurveyResult(String.valueOf(d1));
                    }
                        
                    if (courseScoreCount > 0) {
                        BigDecimal bd = new BigDecimal(scoreTotalScore * 1.0 / courseScoreCount);
                        double d2 =bd.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
                        projectPhaseCourse.setCourseSurveyResult(String.valueOf(d2));
                    }
                    
                    if (!StringUtil.isBlank(suggestion)) {
                        projectPhaseCourse.setSurveySuggestion(suggestion.substring(1));
                    } else {
                        projectPhaseCourse.setSurveySuggestion("");
                    }
                }
                courses.add(projectPhaseCourse);
            }

            modelAndView.addObject("courses", courses);
            modelAndView.addObject("recordCount", courses.size());
            modelAndView.addObject("page", page);

        }

        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));

        return modelAndView;
    }
    
    /**
     * 项目评估结果表 - 导出
     * 
     * @param search
     * @return
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/reports/course-record-report-export", method = RequestMethod.GET)
    @MenuSetting("submenu-course-record")
    public ModelAndView courseRecordReportExport(CourseRecordReportSearch courseRecordReportSearch, Page page) {

        ModelAndView modelAndView = new ModelAndView(
                new ExcelTemplateView("course-record-result.xls", "course-record-report.xls"));
        Login login = (Login) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Principal principal = principalService.loadByEmail(login.getEmail());
        if (principal.getAuthority().equals("ROLE_SUPER_USER")) {
            // 系统管理员
            // do nothing
        } else if (principal.getAuthority().equals("ROLE_DEPARTMENT_USER")) {
            // 事业部负责人
            courseRecordReportSearch.setDepartmentId(principal.getDepartmentId());
        }

        int totals = reportService.count(courseRecordReportSearch);
        if (totals > 0) {

            List courseList = reportService.searchForExport(courseRecordReportSearch);
            List<ProjectPhaseCourse> courses = new ArrayList<ProjectPhaseCourse>();
            for (int i = 0; i < courseList.size(); i++) {
                ProjectPhaseCourse projectPhaseCourse = (ProjectPhaseCourse) courseList.get(i);
                // Course course= projectPhaseCourse.getCourse();
                // set survey result / suggestion to each course
                List<TrainingSurveyResult> trainingSurveyResultList = trainingSurveyResultService
                        .listByProjectPhaseCourse(projectPhaseCourse.getId());
                int trainerTotalScore = 0;
                int scoreTotalScore = 0;
                int trainerScoreCount = 0;
                int courseScoreCount = 0;
                int j = 0;
                String suggestion = "";
                for (; j < trainingSurveyResultList.size(); j++) {
                    TrainingSurveyResult trainingSurveyResult = trainingSurveyResultList.get(j);
                    
                    //check question
                    if (trainingSurveyResult.getQuestion().contains("主题课程是否满足您的期望、对您的管理工作有所帮助？") ||
                            trainingSurveyResult.getQuestion().contains("授课逻辑清晰易懂，呈现演绎生动有趣，能够吸引您积极投入对主题内容的学习？") ||
                                trainingSurveyResult.getQuestion().contains("对主题内容有深度的理解，善于联系真实的工作场景与实际的管理挑战") ||
                                    trainingSurveyResult.getQuestion().contains("主题课程进行整体评价")){
                        int score = 0;
                        try {
                            score = Integer.parseInt(trainingSurveyResult.getInputValue());
                            trainerTotalScore += score;
                            trainerScoreCount++;
                        } catch (Exception exx) {
                            logger.warn(trainingSurveyResult.getQuestion() + ":::::::"
                                    + trainingSurveyResult.getInputValue() + "  " + exx.getMessage());
                        }
                    }
                }
                if (j > 0) {
                    if (trainerScoreCount > 0) {
                        BigDecimal bd = new BigDecimal(trainerTotalScore * 1.0 / (trainerScoreCount));
                        double d1 =bd.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
                        projectPhaseCourse.setTrainerSurveyResult(String.valueOf(d1));
                    }
                        
                    if (courseScoreCount > 0) {
                        BigDecimal bd = new BigDecimal(scoreTotalScore * 1.0 / courseScoreCount);
                        double d2 =bd.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
                        projectPhaseCourse.setCourseSurveyResult(String.valueOf(d2));
                    }
                        
                    projectPhaseCourse.setSurveySuggestion(suggestion);
                }
                courses.add(projectPhaseCourse);
            }

            modelAndView.addObject("results", courses);

        }
        return modelAndView;

    }

}
